#!/usr/bin/perl
use strict;
use DBI;
use HTTP::Date;
use Config::IniFiles;
use XML::LibXML;

require "/var/www/cgi-bin/gnugraph/rcoos/timeZone.lib";
require "/var/www/cgi-bin/gnugraph/rcoos/graphAll.lib";

my $graph_config="/var/myscheduler/graph.xml";
my $xp_graph = XML::LibXML->new->parse_file($graph_config);

my $tmp="/var/www/html/images/images/";
my $pic="test.png";
my $webpic="images/images/test.png";

my $station=$ARGV[0];
my $platform_handle=$ARGV[1];
my $startd=$ARGV[2];
my $endd=$ARGV[3];
my $format=$ARGV[4];
my $sensorId=$ARGV[5];
my $timezone=$ARGV[6];
my $myunit=$ARGV[7];

if($endd){$endd="$endd 23:59:59";}

system("rm $tmp$pic");

my @array1=split(/-/,$format);
my $sort_string=$array1[0]." ".$array1[1];
my $sort_string="m_date asc";

#my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname", "", "",
           #         { RaiseError => 1, AutoCommit => 1 });
#if(!defined $dbh) {die "Cannot connect to database!\n";}
 my $dbh=getdbConn();
 if($dbh==0){ die "Cannot connect to database!\n";}

my ($fixed_z,$mtype_id,$standardname,$definition,$uom,$multiple,$formula);

my $sql="select sensor.fixed_z,m_type.row_id,obs_type.standard_name,obs_type.definition,uom_type.standard_name,obs_type.multiple,sensor.fixed_z from sensor 
         left join m_type on m_type.row_id=sensor.m_type_id
         left join m_scalar_type on m_scalar_type.row_id=m_type.m_scalar_type_id
         left join obs_type on obs_type.row_id=m_scalar_type.obs_type_id
         left join uom_type on uom_type.row_id=m_scalar_type.uom_type_id
         left join platform on sensor.platform_id=platform.row_id
         where sensor.row_id=$sensorId and platform.platform_handle = '$platform_handle'";

 my $sth = $dbh->prepare($sql);
 $sth->execute();
 while (my @row = $sth->fetchrow_array) {
      $fixed_z=$row[0];
      $mtype_id=$row[1];
      $standardname=$row[2];
      $definition=$row[3];
      ($uom,$formula)=uom_convert($myunit,$row[4]);
      $multiple=$row[5];
 }

 if($multiple==0){

 my $sql="select m_date,m_lon,m_lat,m_z,m_value,qc_level from multi_obs where m_date>='$startd' and m_date<='$endd' and (qc_level!=1 or qc_level is null) and sensor_id=$sensorId and m_type_id=$mtype_id and platform_handle='$platform_handle' and m_value is not null order by $sort_string";
 $sth = $dbh->prepare($sql);
 $sth->execute();
 
 my $i=0;

 print "<pre>";
 print "$station ";
 my $dtype=$standardname;
 if($fixed_z){
      if((substr($standardname,0,3)!='Air')&&(substr($standardname,0,4)!='wind')){
         $dtype=$dtype."($fixed_z m)";
      }
 }
 print "$dtype Query Results:\n";
 print "Time Period: $startd ~ ".substr($endd,0,10)."\n";
 print "Standard Name: $definition<br>Unit: $uom \n"; 

 my $graph_data_file =$tmp.'gnuplot_'.int(rand(10000000));

 open (TEMPFILE,">$graph_data_file");

 my $qcflag=0;
 while (my @row = $sth->fetchrow_array) {
     $row[4]=value_convert($formula,$row[4]);
 
     $row[0]=timeConvert($row[0],$timezone);
       
     if($row[5]==2){
        print TEMPFILE "$row[0] \t $row[4] \t $row[4] \n";; 
        $qcflag++;
     }
     else {
        print TEMPFILE "$row[0] \t $row[4] \t  \n"; 
     }
     $i++;
 }

 close TEMPFILE ;

 print "</pre>";

 my $html=$tmp."rcoos.php";
 if(-e $html){
   system("rm $html");
 }
 open (TEMPFILE1,">$html");

 if($i==0){
    system("rm TEMPFILE");
    print TEMPFILE1 "No Data Found";
 }
 else {
    my $title="$station $dtype ($startd ~ ".substr($endd,0,10).")";
    my $units="$uom";

    my $imgname=$tmp.$pic;
    
    my_graphall($graph_data_file, $title, $units, $imgname,$qcflag,$timezone); 
    print TEMPFILE1 "<img src=$webpic?x=<?=uniqid((double)microtime()*1000000,1)?>><br>";
 }
 }
 else {
    my $html=$tmp."rcoos.php";
   if(-e $html){
      system("rm $html");
   }
   open (TEMPFILE1,">$html");
   print TEMPFILE1 "<font color=red>You can not graph this data type.<br></font>";
 }

 close(TEMPFILE1);

 $sth->finish();
 undef $sth;
 $dbh->disconnect();

 sub uom_convert {

 my ($selected,$uom) = @_;

 my $unit_conversion = '';

 ##CONFIG_START
 #conversions for the following which were labeled wrong on the way in to db
 #if ($obs_type eq 'dissolved_oxygen') { $obs_type = 'oxygen_concentration'; }
 #if ($uom eq 'millibar') { $uom = 'mb'; }
 #if ($uom eq 'percent_saturation') { $uom = 'percent'; }
 ##CONFIG_END

  my $y_title="";
  my $conversion_formula="";
  $y_title = $xp_graph->findvalue('//unit_conversion_list/unit_conversion[@id="'.$uom.'_to_'.$selected.'"]/y_title');
  if($y_title eq ""){$y_title=$uom;}
  $conversion_formula = $xp_graph->findvalue('//unit_conversion_list/unit_conversion[@id="'.$uom.'_to_'.$selected.'"]/conversion_formula');
  if($conversion_formula eq ""){
     $conversion_formula="sprintf(\"%.2f\",var1)";
  }
 return ($y_title,$conversion_formula);

}


sub value_convert {

 my ($conversion_string,$measurement) = @_;
    $conversion_string =~ s/var1/$measurement/g;
 my $conversion_val = eval $conversion_string;
 return $conversion_val; 
}

